package com.ruibang.glass.produce.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.produce.constant.Constants;
import com.ruibang.glass.produce.domain.req.CommonTrendChartReq;
import com.ruibang.glass.produce.domain.req.MaterialCharacteristicsReq;
import com.ruibang.glass.produce.domain.resp.MaterialCharacteristicsTrendChart;
import com.ruibang.glass.produce.entity.MaterialCharacteristics;
import com.ruibang.glass.produce.mapper.MaterialCharacteristicsMapper;
import com.ruibang.glass.produce.service.MaterialCharacteristicsService;
import com.ruibang.glass.produce.util.ExcelStyleUtils;
//import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产-理化-物料特性 服务实现类
 * </p>
 *
 * @author songJinKang
 * @since 2024-03-12
 */
@Slf4j
@Service
public class MaterialCharacteristicsServiceImpl extends ServiceImpl<MaterialCharacteristicsMapper, MaterialCharacteristics> implements MaterialCharacteristicsService {
    @Autowired
    private RedisSingleService redisService;
//    @PostConstruct
//    public void initData() {
//        List<MaterialCharacteristics> list = this.list();
//        for (MaterialCharacteristics moistureDeteciton : list) {
//            String auditById = moistureDeteciton.getAuditById();
//            if (StringUtils.isNotBlank(auditById)) {
//                Object auditObj = redisService.hget(RedisKey.USER_GROUP_TYPE, auditById);
//                if (auditObj != null) {
//                    moistureDeteciton.setAuditBy(auditObj.toString());
//                }
//            }
//            String testById = moistureDeteciton.getTestById();
//            if (StringUtils.isNotBlank(testById)) {
//                Object checkObj = redisService.hget(RedisKey.USER_GROUP_TYPE, testById);
//                if (checkObj != null) {
//                    moistureDeteciton.setTestBy(checkObj.toString());
//                }
//            }
//        }
//        updateBatchById(list);
//    }

    @Override
    public IPage<MaterialCharacteristics> pageQuery(MaterialCharacteristicsReq materialCharacteristicsReq) {
        QueryWrapper<MaterialCharacteristics> qw = new QueryWrapper<>();
        qw.lambda().eq(MaterialCharacteristics::getIsDelete, Constants.ZERO_STR);
        if (materialCharacteristicsReq.getStartTime() != null && materialCharacteristicsReq.getEndTime() != null) {
            qw.lambda().ge(MaterialCharacteristics::getSampleTime, materialCharacteristicsReq.getStartTime());
            qw.lambda().le(MaterialCharacteristics::getSampleTime, materialCharacteristicsReq.getEndTime());
        }
        qw.lambda().orderByDesc(MaterialCharacteristics::getCreateTime);
        return this.page(new Page<>(materialCharacteristicsReq.getPageNo(), materialCharacteristicsReq.getPageSize()), qw.lambda());
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(MaterialCharacteristics::getId, id).set(MaterialCharacteristics::getIsDelete, Constants.ONE_STR).update();
    }

    @Override
    public MaterialCharacteristicsTrendChart trendChart(CommonTrendChartReq trendChartReq) {
        //默认查询3天
        if (trendChartReq.getStartTime() == null || trendChartReq.getEndTime() == null) {
            LocalDateTime now = LocalDateTime.now();
            trendChartReq.setStartTime(now.minusDays(3));
            trendChartReq.setEndTime(now);
        }
        //组合数据
        MaterialCharacteristicsTrendChart materialCharacteristicsTrendChart = new MaterialCharacteristicsTrendChart();
        List<MaterialCharacteristics> data = baseMapper.trendChart(trendChartReq);
        if (CollectionUtils.isNotEmpty(data)) {
            materialCharacteristicsTrendChart.setCollectTime(data.stream().map(e -> e.getSampleTime().format(Constants.DATE_TIME_FORMATTER)).collect(Collectors.toList()));
            materialCharacteristicsTrendChart.setData(data);
            //550nm单点透过率
            materialCharacteristicsTrendChart.setF1(data.stream().map(MaterialCharacteristics::getF1).collect(Collectors.toList()));
            //密度(g/cm3)
            materialCharacteristicsTrendChart.setF2(data.stream().map(MaterialCharacteristics::getF2).collect(Collectors.toList()));
            //软化、退火、应变温度
            materialCharacteristicsTrendChart.setF3(data.stream().map(MaterialCharacteristics::getF3).collect(Collectors.toList()));
            materialCharacteristicsTrendChart.setF4(data.stream().map(MaterialCharacteristics::getF4).collect(Collectors.toList()));
            materialCharacteristicsTrendChart.setF5(data.stream().map(MaterialCharacteristics::getF5).collect(Collectors.toList()));
        }
        return materialCharacteristicsTrendChart;
    }

    @Override
    public void export(MaterialCharacteristicsReq materialCharacteristicsReq, HttpServletResponse response) {
        materialCharacteristicsReq.setPageNo(-1);
        materialCharacteristicsReq.setPageSize(-1);
        IPage<MaterialCharacteristics> page = this.pageQuery(materialCharacteristicsReq);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<MaterialCharacteristics> materialCharacteristicsList = page.getRecords();
            try {
                EasyExcel.write(response.getOutputStream(), MaterialCharacteristics.class)
                        .registerWriteHandler(ExcelStyleUtils.createTableStyle())
                        .sheet("history_data").doWrite(materialCharacteristicsList);
            } catch (IOException e) {
                log.error("数据导出失败：{}", e.getMessage());
            }
        }
    }

    @Override
    public void saveInfo(MaterialCharacteristics materialCharacteristics) {
        materialCharacteristics.setIsDelete(Constants.ZERO_STR);
        setUserName(materialCharacteristics);
        this.save(materialCharacteristics);
    }

    @Override
    public void edit(MaterialCharacteristics materialCharacteristics) {
        setUserName(materialCharacteristics);
        this.updateById(materialCharacteristics);
    }

    private void setUserName(MaterialCharacteristics materialCharacteristics) {
        String auditById = materialCharacteristics.getAuditById();
        String checkById = materialCharacteristics.getCheckById();
        String createUserId = materialCharacteristics.getCreateUserId();
        String testById = materialCharacteristics.getTestById();
        if (StringUtils.isNotBlank(testById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, testById);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                materialCharacteristics.setTestBy(userObj.toString());
            }
        } else {
            materialCharacteristics.setTestBy("");
        }
        if (StringUtils.isNotBlank(createUserId)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, createUserId);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                materialCharacteristics.setCreateUserName(userObj.toString());
            }
        } else {
            materialCharacteristics.setCreateUserName("");
        }
        if (StringUtils.isNotEmpty(auditById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, auditById);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                materialCharacteristics.setAuditBy(userObj.toString());
            }
        } else {
            materialCharacteristics.setAuditBy("");
        }
        if (StringUtils.isNotEmpty(checkById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, checkById);
            if (userObj != null && StringUtils.isNotBlank(userObj.toString())) {
                materialCharacteristics.setCheckBy(userObj.toString());
            }
        } else {
            materialCharacteristics.setCheckBy("");
        }
    }

}
